package com.example.hcd.tool;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.Poi;
import com.example.hcd.R;
import com.example.hcd.internet.LinkHelp;
import com.example.hcd.internet.URLS;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Criteria;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class LocationGet extends Activity{
	public LocationManager locationManager;
	private static final String TAG = "GPS Services";
	// 百度定位
	public LocationClient mLocationClient = null;
	public BDLocationListener myListener = new MyLocationListener();

	//WIFI MAC地址
	private String macAdress;

	//签到类型
	private long signType;

	//公司地址
	private String address;

	//经度
	private String longitude;

	//纬度
	private String latitude;

	//时间
	private String time;

	private TextView address_text;
	private TextView time_text;
	private Button sign_btn;
//	private ImageView sign_over;

	private TextView title;

	private boolean isLocationSuccess;

	private boolean isTime;

	String date = null;// 设置默认选中的日期  格式为 “2014-04-05” 标准DATE格式

	public LocationGet() {
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sigh_activity_view);

		ImageView back = (ImageView)findViewById(R.id.title_bar_btn_left);
		back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				mLocationClient.stop();
				finish();
			}
		});

		//
		title = (TextView)findViewById(R.id.title_content);
		address_text = (TextView)findViewById(R.id.address_info);
		time_text = (TextView)findViewById(R.id.percent_time);
		sign_btn = (Button)findViewById(R.id.popupwindow_calendar_bt_enter);
//		sign_over = (ImageView)findViewById(R.id.sign_over);

		sign_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if(signType==1||signType==2)
				{
					if(signType==2&&isTime==false)
					{
						new AlertDialog.Builder(LocationGet.this).setMessage("尚未到今日规定下班时间，您确定下班吗？")
								.setNegativeButton("取消", new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog, int which) {
									}
								}).setPositiveButton("确定", new DialogInterface.OnClickListener()

						{
							public void onClick(DialogInterface dialog, int whichButton) {
								UpdateSignInfo data =new UpdateSignInfo();
								data.execute();
							}
						}).show();
					}else
					{
						UpdateSignInfo data =new UpdateSignInfo();
						data.execute();
					}

				}
			}
		});


		//初始化日历
		final TextView popupwindow_calendar_month = (TextView) findViewById(R.id.popupwindow_calendar_month);
		final KCalendar calendar = (KCalendar)findViewById(R.id.popupwindow_calendar);
//		Button popupwindow_calendar_bt_enter = (Button)findViewById(R.id.popupwindow_calendar_bt_enter);

		popupwindow_calendar_month.setText(calendar.getCalendarYear() + "年"
				+ calendar.getCalendarMonth() + "月");

		if (null != date) {

			int years = Integer.parseInt(date.substring(0,
					date.indexOf("-")));
			int month = Integer.parseInt(date.substring(
					date.indexOf("-") + 1, date.lastIndexOf("-")));
			popupwindow_calendar_month.setText(years + "年" + month + "月");

			calendar.showCalendar(years, month);
			calendar.setCalendarDayBgColor(date,
					R.drawable.calendar_date_focused);
		}

		List<String> list = new ArrayList<String>(); //设置标记列表
		list.add("2014-04-01");
		list.add("2014-04-02");
		calendar.addMarks(list, 0);

		//监听所选中的日期
		calendar.setOnCalendarClickListener(new KCalendar.OnCalendarClickListener() {

			public void onCalendarClick(int row, int col, String dateFormat) {
				int month = Integer.parseInt(dateFormat.substring(
						dateFormat.indexOf("-") + 1,
						dateFormat.lastIndexOf("-")));

				if (calendar.getCalendarMonth() - month == 1//跨年跳转
						|| calendar.getCalendarMonth() - month == -11) {
					calendar.lastMonth();

				} else if (month - calendar.getCalendarMonth() == 1 //跨年跳转
						|| month - calendar.getCalendarMonth() == -11) {
					calendar.nextMonth();

				} else {
					//calendar.removeAllBgColor();
//					calendar.setCalendarDayBgColor(dateFormat,
//							R.drawable.calendar_date_focused);
					date = dateFormat;//最后返回给全局 date
				}
			}
		});

		//监听当前月份
		calendar.setOnCalendarDateChangedListener(new KCalendar.OnCalendarDateChangedListener() {
			public void onCalendarDateChanged(int year, int month) {
				popupwindow_calendar_month
						.setText(year + "年" + month + "月");
			}
		});

		//上月监听按钮
		RelativeLayout popupwindow_calendar_last_month = (RelativeLayout)findViewById(R.id.popupwindow_calendar_last_month);
		popupwindow_calendar_last_month
				.setOnClickListener(new OnClickListener() {

					public void onClick(View v) {
						calendar.lastMonth();
						//更新签到详情
						calendar.updateList(LocationGet.this);
					}

				});

		//下月监听按钮
		RelativeLayout popupwindow_calendar_next_month = (RelativeLayout)findViewById(R.id.popupwindow_calendar_next_month);
		popupwindow_calendar_next_month
				.setOnClickListener(new OnClickListener() {

					public void onClick(View v) {
						calendar.nextMonth();
						//更新签到详情
						calendar.updateList(LocationGet.this);
					}
				});

		mLocationClient = new LocationClient(getApplicationContext());     //声明LocationClient类
		mLocationClient.registerLocationListener(myListener);    //注册监听函数
		mLocationClient.start();
		//registerGPS();

		getWifi();

		//更新签到详情
		calendar.updateList(this);

	}

	private void initLocation(){
		LocationClientOption option = new LocationClientOption();
		option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy
		);//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
		option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
		int span=1000;
		option.setScanSpan(span);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
		option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
		option.setOpenGps(false);//可选，默认false,设置是否使用gps
		option.setLocationNotify(true);//可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
		option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
		option.setIsNeedLocationPoiList(false);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
		option.setIgnoreKillProcess(false);//可选，默认false，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认杀死
		option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
		option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤gps仿真结果，默认需要


		mLocationClient.setLocOption(option);
	}



	public class MyLocationListener implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			//Receive Location
			StringBuffer sb = new StringBuffer(256);
			sb.append("time : ");
			sb.append(location.getTime());

			time = location.getTime();

			time_text.setText("时间:"+time);

			sb.append("\nerror code : ");
			sb.append(location.getLocType());
			sb.append("\nlatitude : ");

			latitude = ""+location.getLatitude();

			sb.append(location.getLatitude());
			sb.append("\nlontitude : ");
			sb.append(location.getLongitude());

			longitude = ""+location.getLongitude();

			sb.append("\nradius : ");
			sb.append(location.getRadius());
			if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
				sb.append("\nspeed : ");
				sb.append(location.getSpeed());// 单位：公里每小时
				sb.append("\nsatellite : ");
				sb.append(location.getSatelliteNumber());
				sb.append("\nheight : ");
				sb.append(location.getAltitude());// 单位：米
				sb.append("\ndirection : ");
				sb.append(location.getDirection());// 单位度
				sb.append("\naddr : ");
				sb.append(location.getAddrStr());
				sb.append("\ndescribe : ");
				sb.append("gps定位成功");

			} else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
				sb.append("\naddr : ");
				sb.append(location.getAddrStr());

				address = location.getAddrStr();

				address_text.setText("地址:"+address);
				//运营商信息
				sb.append("\noperationers : ");
				sb.append(location.getOperators());
				sb.append("\ndescribe : ");
				sb.append("网络定位成功");
				Toast.makeText(LocationGet.this,"网络定位成功",Toast.LENGTH_SHORT).show();

				isLocationSuccess = true;
			} else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
				sb.append("\ndescribe : ");
				sb.append("离线定位成功，离线定位结果也是有效的");
			} else if (location.getLocType() == BDLocation.TypeServerError) {
				sb.append("\ndescribe : ");
				sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
				ToastHelp.doToast(LocationGet.this, "服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因", false);
			} else if (location.getLocType() == BDLocation.TypeNetWorkException) {
				sb.append("\ndescribe : ");
				sb.append("网络不同导致定位失败，请检查网络是否通畅");
				ToastHelp.doToast(LocationGet.this,"网络不同导致定位失败，请检查网络是否通畅",false);
			} else if (location.getLocType() == BDLocation.TypeCriteriaException) {
				sb.append("\ndescribe : ");
				sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
				ToastHelp.doToast(LocationGet.this, "无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机", false);
			}
			sb.append("\nlocationdescribe : ");
			sb.append(location.getLocationDescribe());// 位置语义化信息
			List<Poi> list = location.getPoiList();// POI数据
			if (list != null) {
				sb.append("\npoilist size = : ");
				sb.append(list.size());
				for (Poi p : list) {
					sb.append("\npoi= : ");
					sb.append(p.getId() + " " + p.getName() + " " + p.getRank());
				}
			}

			mLocationClient.stop();
			new LoadSignInfo().execute();
		}

	}

	private void registerGPS() {
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

		if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
			Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivityForResult(intent, 0);
			return;
		}

		String bestProvider = locationManager.getBestProvider(getCriteria(),
				true);

		Location location = locationManager.getLastKnownLocation(bestProvider);
		// Location location=
		// lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
		updateView(location);

		locationManager.addGpsStatusListener(listener);

		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
				1000, 1, locationListener);
		// locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
		// 1000, 1, locationListener);
	}

	private LocationListener locationListener = new LocationListener() {

		public void onLocationChanged(Location location) {
			updateView(location);

		}

		public void onStatusChanged(String provider, int status, Bundle extras) {
			switch (status) {

			case LocationProvider.AVAILABLE:

				break;
			case LocationProvider.OUT_OF_SERVICE:
				break;
			case LocationProvider.TEMPORARILY_UNAVAILABLE:
				break;
			}
		}

		public void onProviderEnabled(String provider) {
			Location location = locationManager.getLastKnownLocation(provider);
			updateView(location);
		}

		public void onProviderDisabled(String provider) {
			updateView(null);
		}

	};

	GpsStatus.Listener listener = new GpsStatus.Listener() {
		public void onGpsStatusChanged(int event) {
			switch (event) {
			case GpsStatus.GPS_EVENT_FIRST_FIX:
				break;
			case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
				GpsStatus gpsStatus = locationManager.getGpsStatus(null);
				int maxSatellites = gpsStatus.getMaxSatellites();
				Iterator<GpsSatellite> iters = gpsStatus.getSatellites()
						.iterator();
				int count = 0;
				while (iters.hasNext() && count <= maxSatellites) {
					GpsSatellite s = iters.next();
					count++;
				}
				break;
			case GpsStatus.GPS_EVENT_STARTED:
				break;
			case GpsStatus.GPS_EVENT_STOPPED:
				break;
			}
		};
	};

	private void updateView(Location location) {
		if (location != null) {
			System.out.println("经度==" + location.getLongitude() + ",维度=="
					+ location.getLatitude());
			
			getWifi();

		} else {
		}
	}

	private Criteria getCriteria() {
		Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_FINE);
		criteria.setSpeedRequired(false);
		criteria.setCostAllowed(false);
		criteria.setBearingRequired(false);
		criteria.setAltitudeRequired(false);
		criteria.setPowerRequirement(Criteria.POWER_LOW);
		return criteria;
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
//		locationManager.removeUpdates(locationListener);
	}

	private static final double EARTH_RADIUS = 6378137;

	private static double rad(double d) {
		return d * Math.PI / 180.0;
	}

	public static double DistanceOfTwoPoints(double lat1, double lng1,
			double lat2, double lng2) {
		double radLat1 = rad(lat1);
		double radLat2 = rad(lat2);
		double a = radLat1 - radLat2;
		double b = rad(lng1) - rad(lng2);
		double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
				+ Math.cos(radLat1) * Math.cos(radLat2)
				* Math.pow(Math.sin(b / 2), 2)));
		s = s * EARTH_RADIUS;
		s = Math.round(s * 10000) / 10000;
		return s;
	}

	public void getWifi() {

		WifiManager wifimanage = (WifiManager) this
				.getSystemService(Context.WIFI_SERVICE);// 获取WifiManager

		// 检查wifi是否开启

		if (wifimanage.isWifiEnabled()) {
//			wifimanage.setWifiEnabled(true);

			WifiInfo wifiinfo = wifimanage.getConnectionInfo();

//			String ip = intToIp(wifiinfo.getIpAddress());
			macAdress= wifiinfo.getBSSID();
			System.out.println("macIp=="+macAdress);
			initLocation();
		}else
		{
			ToastHelp.doToast(LocationGet.this,"请打开WIFI连接在尝试。。。",false);
			finish();
		}

	}
	private class LoadSignInfo extends AsyncTask<String, Integer, String> {
//		private MyLoadingDialog dialog;
		@Override
		protected void onPreExecute() {
//			dialog = new MyLoadingDialog(LocationGet.this, null, "加载中...", false);
		}

		@Override
		protected String doInBackground(String... params) {
			String result = null;
			HttpResponse response = null;
			BufferedReader reader = null;

			try {
				ArrayList<NameValuePair> vs = new ArrayList<NameValuePair>();
				vs.add(new BasicNameValuePair("macAddress", macAdress));
				response = LinkHelp.post(URLS.getSignInfo(), vs, false);
				if (response != null) {

					StatusLine line = response.getStatusLine();
					if (line.getStatusCode() == 200) {
						reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
						StringBuilder sb = new StringBuilder();
						for (String s = reader.readLine(); s != null; s = reader.readLine()) {
							sb.append(s);
						}
						reader.close();
						result = sb.toString();
						System.out.println(result);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (reader != null) {
					try {
						reader.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			return result;
		}

		@Override
		protected void onPostExecute(String result)
		{
//			dialog.dimiss();
			if(result==null)
			{
				ToastHelp.doToast(LocationGet.this, "网络异常！");
				return;
			}
			try
			{
				JSONObject jsonObject = new JSONObject(result);
				if(result.contains("error"))
				{
					ToastHelp.doToast(LocationGet.this, jsonObject.getString("msg"));
				}else
				{
					long rescode = jsonObject.getLong("resCode");

					signType = rescode;
					if(rescode == 1||rescode == 2)
					{
						title.setText(jsonObject.getString("resSign"));

						if(rescode == 2)
						{
							if(jsonObject.getString("resMsg").equals(""))
							{
								isTime = true;
							}
						}


					}else if(rescode == -1)
					{
//						sign_over.setVisibility(View.VISIBLE);
						sign_btn.setText("今天已签到完成");
					}else
					{
						ToastHelp.doToast(LocationGet.this, jsonObject.getString("resMsg"));
					}


				}


			}catch (JSONException e)
			{
				e.printStackTrace();
			}
		}

	}


	private class UpdateSignInfo extends AsyncTask<String, Integer, String> {
		private MyLoadingDialog dialog;
		@Override
		protected void onPreExecute() {
			dialog = new MyLoadingDialog(LocationGet.this, null, "加载中...", false);
		}

		@Override
		protected String doInBackground(String... params) {
			String result = null;
			HttpResponse response = null;
			BufferedReader reader = null;

			try {
				ArrayList<NameValuePair> vs = new ArrayList<NameValuePair>();
				vs.add(new BasicNameValuePair("macAddress", macAdress));
				if(signType==1)
				{
					vs.add(new BasicNameValuePair("signType", "work"));
				}else if(signType==2)
				{
					vs.add(new BasicNameValuePair("signType", "offwork"));
				}

				vs.add(new BasicNameValuePair("signAddress", address));

				vs.add(new BasicNameValuePair("lat", latitude));

				vs.add(new BasicNameValuePair("lon", longitude));


				response = LinkHelp.post(URLS.updeteSignInfo(), vs, false);
				if (response != null) {

					StatusLine line = response.getStatusLine();
					if (line.getStatusCode() == 200) {
						reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
						StringBuilder sb = new StringBuilder();
						for (String s = reader.readLine(); s != null; s = reader.readLine()) {
							sb.append(s);
						}
						reader.close();
						result = sb.toString();
						System.out.println(result);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (reader != null) {
					try {
						reader.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			return result;
		}

		@Override
		protected void onPostExecute(String result)
		{
			dialog.dimiss();
			if(result==null)
			{
				ToastHelp.doToast(LocationGet.this, "网络异常！");
				return;
			}
			try
			{
				JSONObject jsonObject = new JSONObject(result);

				if(result.contains("error"))
				{
					ToastHelp.doToast(LocationGet.this, jsonObject.getString("msg"));
				}else
				{
					if(jsonObject.getLong("resCode") == 1)
					{
						Toast.makeText(LocationGet.this, jsonObject.getString("resMsg"), Toast.LENGTH_SHORT).show();
						finish();
					}else if(jsonObject.getLong("resCode") == -1)
					{
						ToastHelp.doToast(LocationGet.this, "不在签到范围内");
					}
				}


			}catch (JSONException e)
			{
				e.printStackTrace();
			}
		}

	}


}
